package com.genesis.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.genesis.mall.dto.*;
import com.genesis.mall.entity.*;
import com.genesis.mall.mapper.OmsOrderMapper;
import com.genesis.mall.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.genesis.mall.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-08-01
 */
@Slf4j
@Service
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements IOmsOrderService {
    @Autowired
    private IOmsOrderItemService orderItemService;
    @Autowired
    private IUmsMemberReceiveAddressService memberReceiveAddressService;
    @Autowired
    private IOmsCartItemService cartItemService;
    @Autowired
    private IPmsProductService productService;
    @Autowired
    private IPmsProductFullReductionService pmsProductFullReductionService;
    @Autowired
    private ISmsCouponHistoryService couponHistoryService;
    @Autowired
    private ISmsCouponService couponService;
    @Autowired
    private ISmsCouponProductCategoryRelationService couponProductCategoryRelationService;
    @Autowired
    private ISmsCouponProductRelationService couponProductRelationService;

    @Autowired
    private IUmsIntegrationConsumeSettingService iUmsIntegrationConsumeSettingService;

    @Autowired
    private IUmsMemberService memberService;

    @Autowired
    private IOmsOrderSettingService omsOrderSettingService;


    @Autowired
    private IOmsOrderService orderService;

    @Autowired
    private IOmsOrderItemService itemService;

    @Autowired
    private IOmsOrderOperateHistoryService orderOperateHistoryService;

    @Override
    public void cancelUserOrder(Long orderId) {
        //修改订单表的状态
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setId(orderId);
        omsOrder.setStatus(4);
        this.updateById(omsOrder);
    }

    @Override
    public OrderDetailDto detail(Long orderId) {
        //通过id获取订单表数据
        OmsOrder omsOrder = this.getById(orderId);
        OrderDetailDto orderDetailDto = new OrderDetailDto();
        BeanUtils.copyProperties(omsOrder, orderDetailDto);
        //查询改订单id的详情
        LambdaQueryWrapper<OmsOrderItem> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OmsOrderItem::getOrderId, orderId);
        List<OmsOrderItem> orderItemList = orderItemService.list(lqw);
        orderDetailDto.setOrderItemList(orderItemList);
        return orderDetailDto;
    }


    @Override
    public PageDto<OmsOrder> findList(OmsOrderVO orderParam, Integer pageNum, Integer pageSize) {
        Page<OmsOrder> omsOrderPage = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        //下单时间
        if (orderParam.getCreateTime() != null) {
            String start = orderParam.getCreateTime() + " 00:00:00";
            String end = orderParam.getCreateTime() + " 23:59:59";

            LocalDateTime startTime = LocalDateTime.parse(start,
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            LocalDateTime endTime = LocalDateTime.parse(end,
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            lqw.between(OmsOrder::getCreateTime, startTime, endTime);
        }
        //订单编号
        if (StringUtils.isNotEmpty(orderParam.getOrderSn())) {
            lqw.eq(OmsOrder::getOrderSn, orderParam.getOrderSn());
        }
        //订单类型
        if (orderParam.getOrderType() != null) {
            lqw.eq(OmsOrder::getOrderType, orderParam.getOrderType());
        }
        //订单来源
        if (orderParam.getSourceType() != null) {
            lqw.eq(OmsOrder::getSourceType, orderParam.getSourceType());
        }
        //订单状态
        if (orderParam.getStatus() != null) {
            lqw.eq(OmsOrder::getStatus, orderParam.getStatus());
        }
        //收货人/手机号码
        if (StringUtils.isNotEmpty(orderParam.getReceiverKeyword())) {
            // "[1]"代表第1位为数字1，"[3456789]"代表第二位可以为3、4 5 6 7、8 9中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
            String telRegex = "[1][3456789]\\d{9}";
            boolean flag = orderParam.getReceiverKeyword().matches(telRegex);
            if (flag) { //传入的是手机号码
                lqw.eq(OmsOrder::getReceiverPhone, orderParam.getReceiverKeyword());
            } else {
                //传入的是收货人
                lqw.like(OmsOrder::getReceiverName, orderParam.getReceiverKeyword());
            }
        }
        //查找没被删除的订单
        lqw.eq(OmsOrder::getDeleteStatus, 0);

        //执行分页查询
        page(omsOrderPage, lqw);

        PageDto<OmsOrder> omsOrderPageDto = new PageDto<>();
        omsOrderPageDto.setPageNum(pageNum);
        omsOrderPageDto.setPageSize(pageSize);
        omsOrderPageDto.setTotal((int) omsOrderPage.getTotal());
        omsOrderPageDto.setTotalPage((int) omsOrderPage.getPages());
        omsOrderPageDto.setList(omsOrderPage.getRecords());

        return omsOrderPageDto;
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        //将订单删除状态修改为1
        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.in(OmsOrder::getId, ids);
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setDeleteStatus(1);
        update(omsOrder, lqw);
        /*//删除对应的订单信息
        LambdaQueryWrapper<OmsOrderItem> omsOrderItemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        for (Long id : ids) {
            omsOrderItemLambdaQueryWrapper.eq(OmsOrderItem::getOrderId,id);
            itemService.remove(omsOrderItemLambdaQueryWrapper);
        }*/


    }

    @Override
    public void closeOrders(List<Long> ids, String note, HttpServletRequest request) {
        //订单状态修改为4
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setStatus(4);
        LambdaQueryWrapper<OmsOrder> omsOrderLqw = new LambdaQueryWrapper<>();
        omsOrderLqw.in(OmsOrder::getId, ids);
        update(omsOrder, omsOrderLqw);
        //将操作进入订单历史记录
        String tokenHeader = request.getHeader("Authorization");
        String token = tokenHeader.split(" ")[1];
        log.info(token);
        Claims claims = TokenUtil.getClaims(token);
        String adminId = claims.get("adminId").toString();
        String memberId = claims.get("umsMember").toString();

        if (adminId != null) {
            for (Long id : ids) {
                OmsOrderOperateHistory omsOrderOperateHistory = new OmsOrderOperateHistory();
                omsOrderOperateHistory.setOrderId(id);
                omsOrderOperateHistory.setOrderStatus(4);
                omsOrderOperateHistory.setNote("订单关闭:" + note);
                omsOrderOperateHistory.setCreateTime(LocalDateTime.now());
                omsOrderOperateHistory.setOperateMan("后台管理员");
                //添加记录
                orderOperateHistoryService.save(omsOrderOperateHistory);
            }
        } else if (memberId != null) {
            for (Long id : ids) {
                OmsOrderOperateHistory omsOrderOperateHistory = new OmsOrderOperateHistory();
                omsOrderOperateHistory.setOrderId(id);
                omsOrderOperateHistory.setOrderStatus(4);
                omsOrderOperateHistory.setNote("订单关闭:" + note);
                omsOrderOperateHistory.setCreateTime(LocalDateTime.now());
                omsOrderOperateHistory.setOperateMan("用户");
                //添加记录
                orderOperateHistoryService.save(omsOrderOperateHistory);
            }
        } else {
            for (Long id : ids) {
                OmsOrderOperateHistory omsOrderOperateHistory = new OmsOrderOperateHistory();
                omsOrderOperateHistory.setOrderId(id);
                omsOrderOperateHistory.setOrderStatus(4);
                omsOrderOperateHistory.setNote("订单关闭:" + note);
                omsOrderOperateHistory.setCreateTime(LocalDateTime.now());
                omsOrderOperateHistory.setOperateMan("系统");
                //添加记录
                orderOperateHistoryService.save(omsOrderOperateHistory);
            }
        }


    }

    @Override
    public void delivery(List<OmsOrder> deliveryParamList) {
        //遍历集合
        for (OmsOrder omsOrder : deliveryParamList) {
            omsOrder.setStatus(2);  //状态修改为发货
            omsOrder.setDeliveryTime(LocalDateTime.now());//发货时间
            LambdaQueryWrapper<OmsOrder> omsOrderLqw = new LambdaQueryWrapper<>();
            omsOrderLqw.eq(OmsOrder::getId, omsOrder.getOrderId());
            update(omsOrder, omsOrderLqw);

            //添加到订单操作记录表
            OmsOrderOperateHistory omsOrderOperateHistory = new OmsOrderOperateHistory();
            omsOrderOperateHistory.setOrderId(omsOrder.getOrderId());
            omsOrderOperateHistory.setOrderStatus(2);
            omsOrderOperateHistory.setNote("完成发货");
            omsOrderOperateHistory.setCreateTime(LocalDateTime.now());
            //TODO  后台管理员是死数据 需要修改
            omsOrderOperateHistory.setOperateMan("后台管理员");
            //添加记录
            orderOperateHistoryService.save(omsOrderOperateHistory);

        }
    }

    @Override
    public boolean moneyInfo(BigDecimal discountAmount, BigDecimal freightAmount, Long orderId, Integer status) {
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setDiscountAmount(discountAmount);   //折扣金额
        omsOrder.setFreightAmount(freightAmount);    //运费
        omsOrder.setStatus(status);   //状态
        OmsOrder order = getById(orderId);
        BigDecimal payAmount = order.getPayAmount(); //获取该订单应付金额
        BigDecimal subtract = payAmount.add(freightAmount).subtract(discountAmount);  //修改后的应付金额
        omsOrder.setPayAmount(subtract);

        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OmsOrder::getId, orderId);
        //修改订单金额
        update(omsOrder, lqw);
        return subtract.compareTo(BigDecimal.ZERO) == 1;
    }

    @Override
    public void note(Long id, String note, Integer status) {

        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setNote(note);
        omsOrder.setStatus(status);
        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OmsOrder::getId, id);
        update(omsOrder, lqw);

    }

    @Override
    public void receiverInfo(OmsOrder omsOrder) {

        omsOrder.setModifyTime(LocalDateTime.now());
        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OmsOrder::getId, omsOrder.getOrderId());
        update(omsOrder, lqw);
    }

    @Override
    public OmsOrderDto getAllInfoById(Long id) {

        OmsOrder order = getById(id);

        LambdaQueryWrapper<OmsOrderItem> omsOrderItemLqw = new LambdaQueryWrapper<>();
        omsOrderItemLqw.eq(OmsOrderItem::getOrderId, id);
        List<OmsOrderItem> omsOrderItems = itemService.list(omsOrderItemLqw);
        LambdaQueryWrapper<OmsOrderOperateHistory> omsOrderOperateHistoryLqw = new LambdaQueryWrapper<>();
        omsOrderOperateHistoryLqw.eq(OmsOrderOperateHistory::getOrderId, id);
        List<OmsOrderOperateHistory> omsOrderOperateHistories = orderOperateHistoryService.list(omsOrderOperateHistoryLqw);

        OmsOrderDto omsOrderDto = new OmsOrderDto();
        BeanUtils.copyProperties(order, omsOrderDto);
        omsOrderDto.setOrderItemList(omsOrderItems);
        omsOrderDto.setHistoryList(omsOrderOperateHistories);
        return omsOrderDto;
    }

    @Override
    public Map<String, Object> generateConfirmOrder(List<Long> cartIds, HttpServletRequest request) {
        //创建一个返回的map集合
        HashMap<String, Object> resMap = new HashMap<>();
        //获取token
        String header = request.getHeader("Authorization");
        String token = header.substring(6);
        Claims claims = TokenUtil.getClaims(token);
        //获取登录id
        Long memberId = Long.parseLong(claims.get("umsMember").toString());
        //获取收货地址收货地址
        LambdaQueryWrapper<UmsMemberReceiveAddress> memberReceiveAddressLqw = new LambdaQueryWrapper<>();
        memberReceiveAddressLqw.eq(UmsMemberReceiveAddress::getMemberId, memberId);
        List<UmsMemberReceiveAddress> memberReceiveAddress = memberReceiveAddressService.list(memberReceiveAddressLqw);
        resMap.put("memberReceiveAddressList", memberReceiveAddress);


        //查询带优惠信息的购物车数据
        List<CartPromotionItemDto> cartPromotionItemDtos = cartIds.stream().map(cartId -> {
            CartPromotionItemDto cartPromotionItemDto = new CartPromotionItemDto();
            //根据id查询购物车数据
            OmsCartItem cartItem = cartItemService.getById(cartId);
            BeanUtils.copyProperties(cartItem, cartPromotionItemDto);
            //根据购物车中的商品id查询商品信息
            PmsProduct product = productService.getById(cartItem.getProductId());
            cartPromotionItemDto.setGrowth(product.getGiftGrowth());//成长值
            cartPromotionItemDto.setIntegration(product.getGiftPoint());//积分
            cartPromotionItemDto.setProductSubTitle(product.getSubTitle());
            cartPromotionItemDto.setPromotionMessage(PromotionType.values()[product.getPromotionType()].toString());
            cartPromotionItemDto.setRealStock(product.getStock() - product.getLowStock());
            //通过商品id获得促销活动减去的金额
            LambdaQueryWrapper<PmsProductFullReduction> lqw = new LambdaQueryWrapper<>();
            lqw.eq(PmsProductFullReduction::getProductId, cartItem.getProductId());
            PmsProductFullReduction fullReduction = pmsProductFullReductionService.getOne(lqw);
            if (cartPromotionItemDto.getPrice().multiply(BigDecimal.valueOf(cartPromotionItemDto.getQuantity())).intValue() >= fullReduction.getFullPrice().intValue()) {
                cartPromotionItemDto.setReduceAmount(fullReduction.getReducePrice());
            } else {
                cartPromotionItemDto.setReduceAmount(BigDecimal.valueOf(0));
            }

            return cartPromotionItemDto;
        }).collect(Collectors.toList());
        resMap.put("cartPromotionItemList", cartPromotionItemDtos);


        //用户可用优惠券列表
        //通过memberId获取优惠券
        List<CouponHistoryDetailDto> historyDetailDtoList = couponHistoryService.findById(memberId);
        historyDetailDtoList = historyDetailDtoList.stream().map(historyDetailDto -> {
            //优惠券关联商品
            List<SmsCouponProductCategoryRelation> productCategoryRelations = couponProductCategoryRelationService.findByCouponId(historyDetailDto.getCouponId());
            //优惠券关联商品分类
            List<SmsCoupon> coupon = couponService.findByCouponId(historyDetailDto.getCouponId());
            //优惠券关联商品
            List<SmsCouponProductRelation> smsCouponProductRelations = couponProductRelationService.findByCouponId(historyDetailDto.getCouponId());
            historyDetailDto.setCoupon(coupon);
            historyDetailDto.setCategoryRelationList(productCategoryRelations);
            historyDetailDto.setProductRelationList(smsCouponProductRelations);
            return historyDetailDto;
        }).collect(Collectors.toList());
        resMap.put("couponHistoryDetailList", historyDetailDtoList);

        //积分使用规则
        UmsIntegrationConsumeSetting consumeSetting = iUmsIntegrationConsumeSettingService.findOne();
        resMap.put("integrationConsumeSetting", consumeSetting);
        //会员持有的积分
        UmsMember umsMember = memberService.getById(memberId);
        resMap.put("memberIntegration", umsMember.getIntegration());
        //计算的金额
        CalcAmount calcAmount = new CalcAmount();
        //订单商品总金额
        BigDecimal totalAmount = BigDecimal.valueOf(0);
        //活动优惠
        BigDecimal promotionAmount = BigDecimal.valueOf(0);
        for (CartPromotionItemDto cartPromotionItemDto : cartPromotionItemDtos) {
            totalAmount = cartPromotionItemDto.getPrice().multiply(BigDecimal.valueOf(cartPromotionItemDto.getQuantity())).add(totalAmount);
            promotionAmount = cartPromotionItemDto.getReduceAmount().add(promotionAmount);
        }
        //应付金额
        BigDecimal payAmount = totalAmount.subtract(promotionAmount);
        calcAmount.setTotalAmount(totalAmount);
        calcAmount.setPayAmount(payAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        resMap.put("calcAmount", calcAmount);
        return resMap;
    }

    @Override
    @Transactional
    public PageDto<OrderDetailDto> getList(PageDto<OrderDetailDto> pageDto, HttpServletRequest request) {
        //通过token获取memberId
        String header = request.getHeader("Authorization");
        String token = header.substring(6);
        Claims claims = TokenUtil.getClaims(token);
        Long memberId = Long.parseLong(claims.get("umsMember").toString());
        //获取当前登录对象的订单订单分页数据
        Page<OmsOrder> page = new Page<>(pageDto.getPageNum(), pageDto.getPageSize());
        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OmsOrder::getStatus, pageDto.getStatus())
                .eq(OmsOrder::getMemberId, memberId)
                .eq(OmsOrder::getDeleteStatus,0);
        this.page(page, lqw);
        List<OmsOrder> omsOrders = page.getRecords();
        List<OrderDetailDto> orderDetailDtos = omsOrders.stream().map(omsOrder -> {
            OrderDetailDto orderDetailDto = new OrderDetailDto();
            BeanUtils.copyProperties(omsOrder, orderDetailDto);
            LambdaQueryWrapper<OmsOrderItem> orderItemLqw = new LambdaQueryWrapper<>();
            orderItemLqw.eq(OmsOrderItem::getOrderId, omsOrder.getId());
            List<OmsOrderItem> omsOrderItems = orderItemService.list(orderItemLqw);
            orderDetailDto.setOrderItemList(omsOrderItems);
            return orderDetailDto;
        }).collect(Collectors.toList());
        pageDto.setTotal((int) page.getTotal());
        pageDto.setTotalPage((int) page.getPages());
        pageDto.setList(orderDetailDtos);
        return pageDto;
    }

    @Override
    public Map<String,Object> generateOrder(OrderParam orderParam, HttpServletRequest request) {
        //通过token获得memberID
        String header = request.getHeader("Authorization");
        String token = header.substring(6);
        Claims claims = TokenUtil.getClaims(token);
        Long memberId = Long.parseLong(claims.get("umsMember").toString());
        //获得当前用户的信息
        UmsMember member = memberService.getById(memberId);
        //获得购物车数据
        List<OmsCartItem> cartItemList = orderParam.getCartIds().stream().map(cartId -> {
            return cartItemService.getById(cartId);
        }).collect(Collectors.toList());
        //获取使用的优惠券信息
        SmsCoupon coupon = null;
        if (orderParam.getCouponId() != null) {

            coupon = couponService.getById(orderParam.getCouponId());
        }
        //积分规则
        UmsIntegrationConsumeSetting integrationConsume = iUmsIntegrationConsumeSettingService.findOne();
        //订单规则数据
        OmsOrderSetting orderSetting = omsOrderSettingService.get();
        //获取收货地址信息
        UmsMemberReceiveAddress address = memberReceiveAddressService.getById(orderParam.getMemberReceiveAddressId());
        //生成订单id
        String orderSn = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now()) + UUID.randomUUID().toString();
        //订单明细数组
        ArrayList<OmsOrderItem> orderItems = new ArrayList<>();

        //订单表
        BigDecimal payAmount = BigDecimal.valueOf(0);//应付总金额

        BigDecimal totalAmount = BigDecimal.valueOf(0);//订单总金额

        BigDecimal promotionAmount = BigDecimal.valueOf(0); //促销优化金额


        for (OmsCartItem cartItem : cartItemList) {
            cartItem.setDeleteStatus(1);
            OmsOrderItem omsOrderItem = new OmsOrderItem();
            omsOrderItem.setOrderSn(orderSn);//订单编号
            omsOrderItem.setProductId(cartItem.getProductId());//商品id
            omsOrderItem.setProductPic(cartItem.getProductPic());
            omsOrderItem.setProductName(cartItem.getProductName());//商品名称
            omsOrderItem.setProductBrand(cartItem.getProductBrand());//品牌名称
            omsOrderItem.setProductSn(cartItem.getProductSn());//商品编号
            omsOrderItem.setProductPrice(cartItem.getPrice());//商品价格
            omsOrderItem.setProductQuantity(cartItem.getQuantity());//数量
            omsOrderItem.setProductSkuId(cartItem.getProductSkuId());//获得商品skuId
            omsOrderItem.setProductSkuCode(cartItem.getProductSkuCode());//获得商品skuCode
            omsOrderItem.setProductCategoryId(cartItem.getProductCategoryId());//获得商品分类id
            //通过商品id获得促销活动减去的金额
            LambdaQueryWrapper<PmsProductFullReduction> lqw = new LambdaQueryWrapper<>();
            lqw.eq(PmsProductFullReduction::getProductId, cartItem.getProductId());
            PmsProductFullReduction fullReduction = pmsProductFullReductionService.getOne(lqw);
            if (cartItem.getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity())).intValue() >= fullReduction.getFullPrice().intValue()) {
                omsOrderItem.setPromotionAmount(fullReduction.getReducePrice());
            } else {
                omsOrderItem.setPromotionAmount(BigDecimal.valueOf(0));
            }
            BigDecimal realAmount = cartItem.getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity())).subtract(omsOrderItem.getPromotionAmount());
            omsOrderItem.setRealAmount(realAmount);//优惠后的金额
            //通过商品id获得商品信息;
            PmsProduct product = productService.getById(cartItem.getProductId());
            omsOrderItem.setGiftIntegration(product.getGiftPoint() * cartItem.getQuantity());
            omsOrderItem.setGiftGrowth(product.getGiftGrowth() * cartItem.getQuantity());
            omsOrderItem.setProductAttr(cartItem.getProductAttr());
            //加入到订单明细集合中
            orderItems.add(omsOrderItem);
            payAmount = realAmount.add(payAmount);
            totalAmount = cartItem.getPrice().add(totalAmount);
            promotionAmount = promotionAmount.add(omsOrderItem.getPromotionAmount());
        }

        OmsOrder omsOrder = new OmsOrder();

        //向omsOrder中封装数据

        omsOrder.setMemberId(memberId);//用户id
        omsOrder.setCouponId(orderParam.getCouponId());//优惠卷id
        omsOrder.setOrderSn(orderSn);//订单编号
        omsOrder.setCreateTime(LocalDateTime.now());//提交时间
        omsOrder.setMemberUsername(member.getUsername());//用户账号
        omsOrder.setTotalAmount(totalAmount);//订单总金额;
        omsOrder.setFreightAmount(BigDecimal.valueOf(0));//运费
        omsOrder.setPromotionAmount(promotionAmount);//促销金额
        if (orderParam.getUseIntegration() != null) {
            Integer integration = orderParam.getUseIntegration();
            Integer money = integration / 100;
            if (money / totalAmount.intValue() > 0.5) {
                omsOrder.setPromotionAmount(BigDecimal.valueOf(totalAmount.intValue() / 2));
            } else {
                omsOrder.setPromotionAmount(BigDecimal.valueOf(money));//积分金额
            }
        }
        if (coupon != null) {
            omsOrder.setCouponAmount(coupon.getAmount());
        } else {
            omsOrder.setCouponAmount(BigDecimal.valueOf(0));
        }
        payAmount = payAmount.subtract(omsOrder.getCouponAmount()).subtract(omsOrder.getPromotionAmount());
        omsOrder.setPayAmount(payAmount);//支付金额
        omsOrder.setPayType(orderParam.getPayType());//支付方式
        omsOrder.setSourceType(1);//订单来源
        omsOrder.setStatus(0);//支付状态
        omsOrder.setAutoConfirmDay(orderSetting.getConfirmOvertime());//自动确认天数
        omsOrder.setReceiverName(address.getName());
        omsOrder.setReceiverPhone(address.getPhoneNumber());
        omsOrder.setReceiverPostCode(address.getPostCode());
        omsOrder.setReceiverProvince(address.getProvince());
        omsOrder.setReceiverCity(address.getCity());
        omsOrder.setReceiverRegion(address.getRegion());
        omsOrder.setReceiverDetailAddress(address.getDetailAddress());
        omsOrder.setUseIntegration(orderParam.getUseIntegration());

        orderService.save(omsOrder);

        //给订单明细附上order_id
        for (OmsOrderItem orderItem : orderItems) {
            orderItem.setOrderId(omsOrder.getId());
        }

        //批量添加到订单明细表中
        orderItemService.saveBatch(orderItems);

        //删除购物车中这两条数据

        cartItemService.updateBatchById(cartItemList);
        //修改优惠券的使用状态
        if (coupon != null) {
            LambdaQueryWrapper<SmsCouponHistory> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SmsCouponHistory::getCouponId, orderParam.getCouponId());
            SmsCouponHistory couponHistory = couponHistoryService.getOne(lqw);
            couponHistory.setUseStatus(1);
            couponHistoryService.updateById(couponHistory);
        }
        //减少改用户的积分
        if (orderParam.getUseIntegration() != null) {
            member.setIntegration(member.getIntegration() - orderParam.getUseIntegration());
        }
        memberService.updateById(member);
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("order",omsOrder);
        resMap.put("orderItemList",orderItems);
        return resMap;
    }

    ;


}
